const jwt=require('jsonwebtoken');
const errorTypes=require('../constants/error-types')
const userService=require('../service/user.service')
const authService=require('../service/auth.service')
const md5password=require('../utils/password-handle')
const { PUBLIC_KEY } = require('../app/config');

const verifyLogin=async (ctx,next)=>{
  const {name,password}=ctx.request.body;

  if(!name ||!password){
    const error=new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
    return ctx.app.emit('error',error,ctx)
  }

  //判断用户是否存在
  const result=await userService.getUserByName(name)
  const user=result
  if(!user){
    const error=new Error(errorTypes.USER_DOES_NOT_EXISTS);
    return ctx.app.emit('error',error,ctx)
  }

  //密码是否正确
  if(md5password(password)!=user.password){
    const error=new Error(errorTypes.PASSWORD_IS_INCORRECT);
    return ctx.app.emit('error',error,ctx)
  }

  ctx.user=user

  await next()
}

const verifyAuth=async(ctx,next)=>{
  //获取token
  const authorization=ctx.headers.authorization

  if(!authorization){
    const error =new Error(errorTypes.UNAUTHORIZATION)
    return ctx.app.emit('error',error,ctx)
  }

  //验证token
  const token=authorization.replace('Bearer ','')
  try{
    const result =jwt.verify(token,PUBLIC_KEY,{
      algorithms:['RS256']
    })
    // result是一个包含用户名和用户id的对象
    ctx.user=result
 
    await next()
  }catch(err){
    const error =new Error(errorTypes.UNAUTHORIZATION)
    ctx.app.emit('error',error,ctx)
  }
}

const verifyPermission=async(ctx,next)=>{
  //通过params判断要修改的是哪个表的哪条记录
  const [resourceKey]=Object.keys(ctx.params)
  
  const tableName=resourceKey.replace('Id','')
  const resourceId=ctx.params[resourceKey]

  const {id}=ctx.user

  const isPermission=await authService.checkResource(tableName,resourceId,id)
  if(!isPermission){
    const error =new Error(errorTypes.UNPERMISSION)
    return ctx.app.emit('error',error,ctx)
  }

  await next()
}

module.exports={
  verifyLogin,
  verifyAuth,
  verifyPermission
}